package com.example.common.network;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import com.example.common.utils.LogUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RetrofitManager {
    
    private static volatile RetrofitManager instance;
    private Map<String, Retrofit> retrofitMap;
    private TokenRefreshInterceptor.TokenRefreshCallback tokenRefreshCallback;
    
    private RetrofitManager() {
        retrofitMap = new ConcurrentHashMap<>();
        initDefaultRetrofit();
    }
    
    public static RetrofitManager getInstance() {
        if (instance == null) {
            synchronized (RetrofitManager.class) {
                if (instance == null) {
                    instance = new RetrofitManager();
                }
            }
        }
        return instance;
    }
    
    /**
     * 设置Token刷新回调
     */
    public void setTokenRefreshCallback(TokenRefreshInterceptor.TokenRefreshCallback callback) {
        this.tokenRefreshCallback = callback;
    }
    
    /**
     * 初始化默认Retrofit实例
     */
    private void initDefaultRetrofit() {
        String mainBaseUrl = NetworkConfig.getMainBaseUrl();
        if (mainBaseUrl != null) {
            createRetrofit(NetworkConfig.API_MAIN, mainBaseUrl);
        }
    }
    
    /**
     * 创建指定API类型的Retrofit实例
     */
    public Retrofit createRetrofit(String apiType, String baseUrl) {
        if (retrofitMap.containsKey(apiType)) {
            return retrofitMap.get(apiType);
        }
        
        Gson gson = new GsonBuilder()
                .setLenient()
                .serializeNulls()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
        
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(OkHttpClientManager.getInstance().getOkHttpClient(tokenRefreshCallback))
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();
        
        retrofitMap.put(apiType, retrofit);
        LogUtil.d("RetrofitManager", "Retrofit created for " + apiType + " with base URL: " + baseUrl);
        
        return retrofit;
    }
    
    /**
     * 获取指定API类型的Retrofit实例
     */
    public Retrofit getRetrofit(String apiType) {
        Retrofit retrofit = retrofitMap.get(apiType);
        if (retrofit == null) {
            String baseUrl = NetworkConfig.getBaseUrl(apiType);
            if (baseUrl != null) {
                retrofit = createRetrofit(apiType, baseUrl);
            } else {
                throw new IllegalArgumentException("Unknown API type: " + apiType);
            }
        }
        return retrofit;
    }
    
    /**
     * 获取默认Retrofit实例（主API）
     */
    public Retrofit getRetrofit() {
        return getRetrofit(NetworkConfig.API_MAIN);
    }
    
    /**
     * 创建指定API类型的服务
     */
    public <T> T createService(Class<T> serviceClass, String apiType) {
        return getRetrofit(apiType).create(serviceClass);
    }
    
    /**
     * 创建默认API服务
     */
    public <T> T createService(Class<T> serviceClass) {
        return createService(serviceClass, NetworkConfig.API_MAIN);
    }
    
    /**
     * 清除所有Retrofit实例
     */
    public void clearAllRetrofits() {
        retrofitMap.clear();
        LogUtil.d("RetrofitManager", "All Retrofit instances cleared");
    }
    
    /**
     * 重新初始化指定API类型的Retrofit实例
     */
    public void reinitRetrofit(String apiType) {
        retrofitMap.remove(apiType);
        String baseUrl = NetworkConfig.getBaseUrl(apiType);
        if (baseUrl != null) {
            createRetrofit(apiType, baseUrl);
        }
        LogUtil.d("RetrofitManager", "Retrofit reinitialized for " + apiType);
    }
}